package org.example.node;

/**
 * @author liyishan
 * @date 2024/8/13 11:06
 * @apiNote
 */

public class Test00019RemoveNthFromEnd {

    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(3);
        head.next.next.next = new ListNode(4);
        head.next.next.next.next = new ListNode(5);
        int n = 2;
        ListNode res = FindKthToTail(head, n);
        while (res!= null) {
            System.out.print(res.val + " -> ");
            res = res.next;
        }
        System.out.println("null");
    }
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode dummy = new ListNode(0, head);
        ListNode first = head;
        ListNode second = dummy;
        for(int i = 0;i<n;i++){
            first = first.next;
        }
        while(first!=null){
            first = first.next;
            second = second.next;
        }
        second.next = second.next.next;
        return dummy.next;
    }

    public static ListNode FindKthToTail (ListNode pHead, int k) {
        // write code here
        ListNode dummpy = new ListNode(-1);
        dummpy.next = pHead;
        ListNode slow = dummpy;
        ListNode fast = pHead;
        for(int i=0;i<k;i++){
            if(fast != null){
                fast = fast.next;
            }else{
                return null;
            }
        }
        while(fast != null){
            fast = fast.next;
            slow = slow.next;
        }
        return slow.next;
    }
}
